package com.hhxy.service.impl;

import com.hhxy.domain.LoginUser;
import com.hhxy.domain.User;
import com.hhxy.service.LoginService;
import com.hhxy.utils.JwtUtil;
import com.hhxy.utils.RedisCache;
import com.hhxy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author ghp
 * @date 2023/3/8
 * @title
 * @description 自定义一个LoginService，用于登录认证
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录
     */
    @Override
    public ResponseResult login(User user) {
        // 1、将用户名和密码封装成Authentication对象
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 2、获取AuthenticationManager的authenticate方法进行认证
        Authentication authentication = authenticationManager.authenticate(token);
        // 3、判断认证是否成功
        if (Objects.isNull(authentication)) {
            // 3.1 认证不成功
            throw new RuntimeException("登录失败！");
        }
        // 3.2 认证成功, 根据 userId生成 jwt
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        // 4、将完整的用户信息存入redis中（减少数据库的压力）
        redisCache.setCacheObject("login:" + userId, loginUser, 30, TimeUnit.MINUTES);

        // 5、返回成功登录后的信息
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResponseResult(200, "登录成功", map);
    }

    /**
     * 退出
     */
    @Override
    public ResponseResult logout() {
        // 获取SecurityContextHolder中的 userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        // 删除 Redis 中的用户信息
        redisCache.deleteObject("login:" + userId);
        return new ResponseResult(200, "退出成功");
    }
}
